<template>
  <div class="consultation">
    <h2>试题管理</h2>
    <div class="flex-center">
      <el-button class="ml0" size="mini" type="success" @click="addQuestion"
        >新增试题</el-button
      >
      <el-select
        size="mini"
        clearable
        v-model="filter.hard"
        placeholder="难度系数"
      >
        <el-option
          v-for="item in options"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        >
        </el-option>
      </el-select>
      <el-select size="mini" clearable v-model="filter.type" placeholder="类型">
        <el-option
          v-for="item in optionsType"
          :key="item"
          :label="item"
          :value="item"
        >
        </el-option>
      </el-select>
      <el-input v-model="key" size="mini" style="width: 120px;" placeholder="关键字/词查询"></el-input>
      <el-button
        class="ml0"
        size="mini"
        type="primary"
        @click="refreshTable('init')"
        >查询</el-button
      >
    </div>
    <div class="consultation-block">
      <div class="table">
        <el-table size="mini" :data="tableData" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="name" label="试题名称" :formatter="formatter">
          </el-table-column>
          <el-table-column prop="score" label="分数"> </el-table-column>
          <el-table-column
            prop="hard"
            label="难度系数"
            :formatter="formatterHard"
          >
          </el-table-column>
          <el-table-column prop="type" label="类型"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                type="warning"
                size="mini"
                @click="updateQuestion(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="deleteQuestion(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          @current-change="refreshTable"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="addForm.id ? '编辑' : '新增'"
      :visible.sync="isAddVisible"
      :close-on-click-modal="false"
      width="50%"
      :before-close="handleAddClose"
    >
      <el-form
        :model="addForm"
        status-icon
        :rules="rules"
        size="mini"
        ref="addForm"
        label-width="100px"
      >
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="addForm.type">
            <el-radio :label="item" v-for="item in optionsType" :key="item">{{ item }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="试题名称" prop="name">
          <vue-editor
            :editorOptions="editorOption"
            v-model="addForm.name"
            useCustomImageHandler
            @image-added="handleImageAdded"
          />
        </el-form-item>
        <el-form-item
          label="选项"
          prop="selections"
          v-if="addForm.type != '主观题' && addForm.type != '填空'"
        >
          <el-button type="primary" @click="addSel">添加选项</el-button>
          (勾选代码本题的答案)
          <div
            v-for="(sel, index) in addForm.selections"
            :key="index"
            class="row"
          >
            <el-checkbox v-model="sel.checked"></el-checkbox>
            <vue-editor
              :editorOptions="editorOption"
              style="height: 250px;width:80%;"
              v-model="sel.text"
              useCustomImageHandler
              @image-added="handleImageAdded"
            />
            <div class="delete" @click="deleteSel(index)">删除</div>
          </div>
        </el-form-item>
        <el-form-item
          label="答案"
          prop="selections"
          v-if="addForm.type == '填空'"
        >
          <el-button type="primary" @click="addSel">添加填空项</el-button>
          <div
            v-for="(sel, index) in addForm.selections"
            :key="index"
            class="flex-center mt10"
          >
            <el-input style="width: 80%;" v-model="sel.text"></el-input>
            <div class="delete" @click="deleteSel(index)">删除</div>
          </div>
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input type="text" v-model="addForm.score"></el-input>
        </el-form-item>
        <el-form-item label="难度系数" prop="hard">
          <el-radio-group v-model="addForm.hard">
            <el-radio label="1">简单</el-radio>
            <el-radio label="2">中等</el-radio>
            <el-radio label="3">困难</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addQuestion,
  getQuestion,
  deleteQuestion,
  updateQuestion,
} from "../service.js";
import { VueEditor } from "vue2-editor";

export default {
  components: { VueEditor },
  name: "question",
  mounted() {
    this.refreshTable();
  },
  data() {
    return {
      tableData: [],
      currentPage: 1,
      options: [
        {
          key: "1",
          label: "简单",
        },
        {
          key: "2",
          label: "中等",
        },
        {
          key: "3",
          label: "困难",
        },
      ],
      optionsType: ["填空", "单选", "多选", "判断", "主观题"],
      pageSize: 10,
      total: 0,
      isVisible: false,
      isAddVisible: false,
      dialogTitle: "",
      key: '',
      addForm: {},
      rules: {
        name: [
          { required: true, message: "试题名称不能为空", trigger: "blur" },
        ],
        score: [{ required: true, message: "分数不能为空", trigger: "blur" }],
      },
      filter: {
        hard: "",
        type: "",
      },
      editorOption: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ align: [] }], //对齐方式
            ["clean"], //清除字体样式
            ['image'] //上传图片
          ],
        },
        placeholder: "输入内容...",
      },
    };
  },
  methods: {
    handleAddClose() {
      this.isAddVisible = false;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (
            !this.addForm.selections.length &&
            this.addForm.type != "主观题"
          ) {
            this.$message.error("请添加选项");
            return;
          }
          if (
            !this.addForm.selections.filter((v) => v.checked).length &&
            this.addForm.type != "主观题" && this.addForm.type != "填空"
          ) {
            this.$message.error("请选择答案");
            return;
          }
          if (this.addForm.type == "填空" && !this.addForm.selections.length) {
            this.$message.error("请添加填空项");
            return;
          }
          if (
            this.addForm.selections.filter((v) => v.checked).length > 1 &&
            (this.addForm.type == "判断" || this.addForm.type == "单选")
          ) {
            this.$message.error("只能有一个正确答案");
            return;
          }
          let params = JSON.parse(JSON.stringify(this.addForm));
          if (this.addForm.type == "主观题") {
            params.selections = "";
          } else {
            params.selections = JSON.stringify(params.selections);
          }
          if (this.addForm.id) {
            updateQuestion(params.id, params).then((res) => {
              if (res.code == 200) {
                this.$message.success("修改成功");
                this.isAddVisible = false;
                this.refreshTable();
              } else {
                this.$message.error(res.msg[0].msg);
              }
            });
          } else {
            addQuestion(params).then((res) => {
              if (res.code == 200) {
                this.$message.success("添加成功");
                this.isAddVisible = false;
                this.refreshTable();
              } else {
                this.$message.error(res.msg[0].msg);
              }
            });
          }
        }
      });
    },
    refreshTable(init = false) {
      if (init == "init") {
        this.currentPage = 1;
      }
      let params = {
        pageSize: this.pageSize,
        page: this.currentPage,
      };
      if (this.filter.hard) {
        params.hard = this.filter.hard;
      }
      if (this.key) {
        params.key = this.key;
      }
      if (this.filter.type) {
        params.type = this.filter.type;
      }
      getQuestion(params).then((res) => {
        this.tableData = res.code === 200 ? res.data.data : [];
        this.total = res.data.total;
      });
    },
    addQuestion() {
      this.addForm = {
        name: "",
        selections: [],
        type: "填空",
        score: "",
        hard: "1",
      };
      this.isAddVisible = true;
      this.$nextTick(() => {
        this.$refs["addForm"].resetFields();
      });
    },
    deleteQuestion(row) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteQuestion(row.id).then((res) => {
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.isVisible = false;
            this.refreshTable();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    updateQuestion(row) {
      this.addForm = JSON.parse(JSON.stringify(row));
      if (this.addForm.selections) {
        this.addForm.selections = JSON.parse(this.addForm.selections);
      } else {
        this.addForm.selections = [];
      }
      this.isAddVisible = true;
    },
    addSel() {
      this.addForm.selections.push({
        text: "",
        checked: false,
      });
    },
    deleteSel(index) {
      this.addForm.selections.splice(index, 1);
    },

    // 处理富文本编辑框的图片
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData();
      formData.append("file", file);
      var xhr = new XMLHttpRequest();
      xhr.open("post", "http://localhost:3000/upload");
      xhr.send(formData);
      xhr.onload = function () {
        if (xhr.status == 200) {
          let res = JSON.parse(xhr.responseText);
          const url = "http://localhost:3000/" + res.url;
          Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
        }
      };
    },
    formatter(row) {
      return this.formatStr(row.name);
    },
    formatterHard(row) {
      return this.options.find((v) => v.key == row.hard).label;
    },
    formatStr(htmlString) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(htmlString, "text/html");
      // 获取<p>元素
      const pElement = doc.querySelector("p");
      // 提取<p>元素的文本内容
      const textContent = pElement.textContent || pElement.innerText; // 兼容不同浏览器
      return textContent.trim();
    },
  },
};
</script>

<style lang="scss" scoped>
h2 {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
.consultation-block {
  width: 90%;
  margin-left: 5%;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.edit {
  color: #409eff;
  cursor: pointer;
}
.delete {
  color: #f56c6c;
  cursor: pointer;
}
.row {
  display: flex;
  gap: 20px;
  margin-top: 8px;
  margin-bottom: 60px;
}
</style>
